﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace library
{
    public class DictionaryCache<TKey, TValue> : Dictionary<TKey, TValue>
    {
        List<DictionaryCacheItem<TKey, TValue>> data = new List<DictionaryCacheItem<TKey, TValue>>();

        public  List<DictionaryCacheItem<TKey, TValue>> Data
        {
            get
            {
                refresh();

                return data;
            }
        }

        protected double Timeout;

        public DictionaryCache(double timeout)
        {
            Timeout = timeout;
        }

        public void Add(TKey key, TValue value)
        {
            lock (data)
            {
                data.Add(new DictionaryCacheItem<TKey, TValue>(key, value));
            }
        }

        void refresh()
        {
            lock (data)
                data = data.Where(x => DateTime.Now.Subtract(x.DateTime).TotalSeconds < Timeout).ToList();
        }

        public class DictionaryCacheItem<TKey, TValue>
        {
            internal DateTime DateTime;

            internal TKey Key;

            internal TValue Value;

            internal DictionaryCacheItem(TKey key, TValue value)
            {
                Key = key;
                
                Value = value;

                DateTime = DateTime.Now;
            }
        }
    }
}
